package com.common.util;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import com.common.domain.entity.FileManage;
import com.common.domain.entity.JsonResult;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.multipart.MultipartFile;


@Slf4j
public class FileUtil {
    public static final long IMG_MAX_SIZE = 10L*1024*1024;
	private static String rootDir= "/u01/Server/imgbase" +File.separator;


	public static final List<String> fileTypeList = Arrays.asList("jpg", "jpeg", "gif","ai", "pdg", "bmp", "png","xls","doc");
	public static final List<String> imageTypeList = Arrays.asList("jpg", "jpeg", "gif","ai", "pdg", "bmp", "raw","tiff","png");

	public static JsonResult<FileManage> uploadFileManageUtil(MultipartFile multipartFile,Long dataId,String dataTableCode,String dirName,int i){

		JsonResult<FileManage> resultVo = new JsonResult<FileManage>();
		SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd");
		String saveDirname=dirName+format.format(new Date())+File.separator;
		dirName=rootDir+saveDirname;

		try{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			String date=sdf.format(new Date());
			String fileOriginalName = multipartFile.getOriginalFilename();
			String fileExtension = fileOriginalName.substring(fileOriginalName.lastIndexOf(".") + 1, fileOriginalName.length());
			String fileName="";
			if (!fileTypeList.contains(fileExtension.toLowerCase())) {
				resultVo.setSuccess(false);
				resultVo.setInfo("上传文件格式不支持");
				log.error("上传文件失败"+fileOriginalName+"格式不支持");
				return resultVo;
			}
			if (fileTypeList.contains(fileExtension.toLowerCase())) {
				fileName=date+"_"+(i++);
				resultVo = uploadFile(dirName, fileName, multipartFile, true);
			}
			if (resultVo.isSuccess()) {
				fileName=resultVo.getDataObject().toString();
				String filePath = saveDirname+fileName;
				FileManage fileManage=new FileManage();
				fileManage.setDataId(dataId);
				fileManage.setFileOriginalName(fileOriginalName);
				fileManage.setDataTableCode(dataTableCode);
				fileManage.setFileExtension(fileExtension);
				fileManage.setFileType(getFileType(fileExtension));
				fileManage.setFileName(fileName);
				fileManage.setFilePath(filePath);
				resultVo.setData(fileManage);
				log.info(fileManage.getDataTableCode());
			}else {
				resultVo.setSuccess(false);
				resultVo.setInfo("======第"+i+"个文件上传失败======");
			}
		} catch (Exception e) {
			resultVo.setSuccess(false);
			resultVo.setInfo("======文件上传失败======");
			log.error("上传文件失败", e);
		}
		return resultVo;
	}

	/**
	 * 文件上传
	 *
	 * @param request
	 * @param uploadPath
	 * @param isImg
	 * @return
	 */
	public static JsonResult<FileManage> uploadFile(String basePath, String newName,MultipartFile file, boolean isImg) {
		// 验证文件
		JsonResult<FileManage> resultVo = validateFile(file, isImg);
		if (resultVo.isSuccess()) {
			// 上传文件
			resultVo = uploadFile(file, basePath, newName,isImg);
		}
		return resultVo;
	}

	/**
	 * 文件下载
	 *
	 * @param path
	 * @param response
	 */
	public static void downLoadFile(String path, HttpServletResponse response) {
		try (InputStream fis = new BufferedInputStream(new FileInputStream(path));
			 ){
			File file = new File(path);
			String filename = file.getName();

			IOUtils.copy(fis,response.getOutputStream());
			response.addHeader("Content-Disposition", "attachment;filename="
					+ new String(filename.getBytes("gbk"), "iso8859-1"));
			response.addHeader("Content-Length", "" + file.length());
			response.setContentType("application/octet-stream");

		} catch (IOException ex) {
			log.error(ex.getMessage(),ex);
		}
	}

	private static JsonResult<FileManage> validateFile(MultipartFile file, boolean isImg) {
		JsonResult<FileManage> resultVo = new JsonResult<FileManage>();
		resultVo.setSuccess(true);
		if (file.isEmpty()) {
			resultVo.setSuccess(false);
			resultVo.setInfo("文件不存在");
			return resultVo;
		}

		String fileOriginalName = file.getOriginalFilename();
		String fileExtension = fileOriginalName.substring(
				fileOriginalName.lastIndexOf(".") + 1, fileOriginalName.length());
		long size = file.getSize();
		if (isImg && !fileTypeList.contains(fileExtension.toLowerCase())) {
			resultVo.setSuccess(false);
			resultVo.setInfo("");
		} else if (isImg && size > IMG_MAX_SIZE) {
			resultVo.setSuccess(false);
			resultVo.setInfo("");
		}
		return resultVo;
	}

	private static JsonResult<FileManage> uploadFile(MultipartFile file, String basePath,String newName,boolean isImg) {
		JsonResult<FileManage> resultVo = new JsonResult<FileManage>();

		String dbfilePath = "";
		try {
			//String dateStr = "";
			String fileName = file.getOriginalFilename();

			//转义拆分重命名文件
			String[] strArr=fileName.split("\\.");

			dbfilePath = newName+"."+strArr[1];
			File uploadFile = new File(basePath + dbfilePath);

			File dest = new File(new File(basePath + dbfilePath).getAbsolutePath());

			log.info("图片地址："+dest.getAbsolutePath());
			// 创建目录
			if (!dest.exists()) {
				dest.getParentFile().mkdirs();// 目录不存在的情况下，创建目录。
			}
			file.transferTo(dest);
			resultVo.setSuccess(true);
			resultVo.setInfo("上传成功");
			resultVo.setDataObject(dbfilePath);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			resultVo.setSuccess(false);
			resultVo.setInfo("上传失败");
			log.error("上传文件出现异常",e);
		}
		return resultVo;
	}
	public static void downLoad(HttpServletResponse response,String filePath){
		//转义拆分重命名文件
		String[] strArr=filePath.split("\\.");
		String fileType=strArr[1];

		if (imageTypeList.contains(fileType)) {
			PrintWriterImage(response, filePath,fileType);
		}else {
			downLoadFile(filePath, response);
		}
	}

	public static void PrintWriterImage(HttpServletResponse response,
			String outImg,String fileType){
		try {
			File file = new File("");
			String path = file.getCanonicalPath();
			System.out.println(path);
			File file1 = new File(outImg);

			BufferedImage image = ImageIO.read(file1);
			ImageIO.write(image, fileType, response.getOutputStream());
		} catch (IOException e) {
			log.error(e.getMessage(),e);
			log.error("获取图片出现异常", e);
		}
	}

	public static String getFileType(String fileExtension) throws ParseException {
		List<String> wordTypeList =Arrays.asList("doc","docx");
		List<String> excelTypeList =Arrays.asList("xls","xlsx");
		List<String> pdfTypeList =Arrays.asList("pdf");
		if (wordTypeList.contains(fileExtension.toLowerCase())) {
			return "word文件";
		}
		if (excelTypeList.contains(fileExtension.toLowerCase())) {
			return "excel文件";
		}
		if (pdfTypeList.contains(fileExtension.toLowerCase())) {
			return "pdf文件";
		}
		if (imageTypeList.contains(fileExtension.toLowerCase())) {
			return "图片文件";
		}
		return "其他文件";
	}

	/**
	 * @Title: uploadBase64
	 * @Description 上传BASE64
	 * @param dataId
	 * @param fileOriginalName
	 * @param dataTableCode
	 * @param dirName
	 * @param fileStr
	 * @param userid
	 * @param i
	 * @return
	 */
	public static JsonResult<FileManage> uploadBase64(Long dataId,String fileOriginalName,String dataTableCode,String dirName,String fileStr,int i) {
//		TODO
		JsonResult<FileManage> resultVo = new JsonResult<FileManage>();
		SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd");
		String saveDirname=dirName+format.format(new Date())+File.separator;
		dirName=rootDir+saveDirname;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String date=sdf.format(new Date());
		String fileExtension = fileOriginalName.substring(fileOriginalName.lastIndexOf(".") + 1, fileOriginalName.length());
		String fileName="";
		if (!fileTypeList.contains(fileExtension.toLowerCase())) {
			resultVo.setSuccess(false);
			resultVo.setInfo("上传文件格式不支持");
			log.error("上传文件失败"+fileOriginalName+"格式不支持");
			return resultVo;
		}
		if (fileTypeList.contains(fileExtension.toLowerCase())) {
			fileName=date+"_"+(i++)+"."+fileExtension;
		}
		// 检查文件目录，不存在则创建
		File folder = new File(dirName);
		if (!folder.exists()) {
			folder.mkdirs();
		}
		// 目标文件
		File destFile = new File(folder, fileName);
		try(FileOutputStream		out = new FileOutputStream(destFile);) {
			out.write(Base64Util.decode(fileStr));
			out.flush();
			FileManage fileManage = new FileManage();
			String filePath = saveDirname+fileName;
			fileManage.setDataId(dataId);
			fileManage.setFileOriginalName(fileOriginalName);
			fileManage.setDataTableCode(dataTableCode);
			fileManage.setFileExtension(fileExtension);
			fileManage.setFileType(getFileType(fileExtension));
			fileManage.setFileName(fileName);
			fileManage.setFilePath(filePath);
			resultVo.setSuccess(true);
			resultVo.setData(fileManage);
			log.info(fileManage.getDataTableCode());

		} catch (Exception e) {
			resultVo.setSuccess(false);
			resultVo.setInfo("======第"+i+"个文件上传失败======");
			log.error(e.getMessage(),e);
		}
		return resultVo;
	}
}
